package com.example.demo.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class WebLogAsp {

    private Logger logger = LoggerFactory.getLogger(WebLogAsp.class);

    /*
     * @Author MRC
     * @Description 定义切入点
     * @Date 10:12 2019/11/9
     * @Param []
     * @return void
     **/
    @Pointcut("execution(public * com.example.demo.controller.*.*(..))")
    public void controllerLog() {
    }

    /**
     * @return void
     * @Author MRC
     * @Description 前置通知
     * @Date 10:14 2019/11/9
     * @Param []
     **/
    @Before("controllerLog()")
    public void beforeAdvice(JoinPoint joinPoint) {

        logger.info("前置通知开始--->");
        /*获取当前请求的HttpServletRequest*/
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        logger.info("URL-->" + request.getRequestURL().toString());
        logger.info("IP-->" + request.getRemoteAddr());
        logger.info("HTTP_Method-->" + request.getMethod());
        logger.info("Request_args-->" + Arrays.toString(joinPoint.getArgs()));

        logger.info("前置通知结束--->");
    }

    @After("controllerLog()")
    public void afterAdvice(JoinPoint joinPoint) {
        logger.info("最终通知--->");
    }

    /**
     * 环绕通知
     *
     * @param proceedingJoinPoint
     * @return
     */
    @Around("controllerLog()")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        logger.info("环绕通知开始-->");
        Object result = null;

        /*proceed()方法表示连接点方法执行 result 为连接点方法的返回值*/
        result = proceedingJoinPoint.proceed();
        logger.info("环绕通知返回值-->" + result);

        logger.info("环绕通知结束-->");
        return result;
    }

    /**
     * @return void
     * @Author MRC
     * @Description 后置通知
     * @Date 11:04 2019/11/9
     * @Param [obj]
     **/
    @AfterReturning(value = "controllerLog()", returning = "obj")
    public void afterReturning(JoinPoint joinPoint, Object obj) {
        logger.info("后置通知正常返回-->" + obj);
    }

    /**
     * @return void
     * @Author MRC
     * @Description 异常通知
     * @Date 11:09 2019/11/9
     * @Param [joinPoint, ex]
     **/
    @AfterThrowing(value = "controllerLog()", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Exception ex) {
        logger.info("异常通知-->" + ex.getMessage());
    }

}